import { useRef, useEffect, useCallback } from 'react';

export function useThrottle(fn, delay, deps = []) {
  // 将变量缓存起来
  // 备注：createRef 每次渲染都会返回一个新的引用，而 useRef 每次都会返回相同的引用。
  const { current } = useRef({ timer: null, fn });

  //如果方法改变,重新赋值
  useEffect(() => {
    current.fn = fn;
  }, [current.fn, fn]);

  return useCallback((...args) => {
    if (current.timer) return;
    current.timer = setTimeout(() => {
      delete current.timer;
    }, delay);
    current.fn && current.fn.apply(this, args);
  }, [current.fn, current.timer, delay]);
}

export function useDebounce(fn, delay, dep = []) {
  const { current } = useRef({ fn, timer: null });
  useEffect(() => {
    current.fn = fn;
  }, [current.fn, fn]);

  return useCallback((...args) => {
    if (current.timer) clearTimeout(current.timer);
    current.timer = setTimeout(() => {
      current.fn && current.fn.apply(this, args);
      delete current.timer;
    }, delay);
  }, [current.fn, current.timer, delay]);
}
